//
//  WLUserCenterController.m
//  WanLian
//
//  Created by muzhuang on 2018/10/8.
//  Copyright © 2018年 wanlian. All rights reserved.
//

#import "WLUserCenterController.h"
#import "WLDatePicker.h"
#import "WLGenderSelectView.h"
#import "WLUserInfoModifyVController.h"
#import "WLUserHeadVController.h"

@interface WLUserCenterController ()<UITableViewDelegate,UITableViewDataSource,WLDatePickerDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
{
    NSArray *arrTitles;
}

@property (nonatomic, strong) WLUserInfo *user;
@property (nonatomic, strong) UITableView *tbUserInfo;

@end

@implementation WLUserCenterController

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    _user = [[WLUseManager shareUser] getUserInformation];
    [_tbUserInfo reloadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"个人资料";
    
//    _user = [[WLUseManager shareUser] getUserInformation];
    arrTitles = @[@[@"头像", @"昵称", @"性别", @"生日", @"邮箱"],@[@"手机号"]];
    _tbUserInfo = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    _tbUserInfo.backgroundColor = wlBackColor;
    _tbUserInfo.scrollEnabled = NO;
    _tbUserInfo.delegate = self;
    _tbUserInfo.dataSource = self;
    _tbUserInfo.rowHeight = WLScaleX(56);
    if (@available(iOS 11.0, *)) {
        _tbUserInfo.estimatedSectionHeaderHeight = 0;
        _tbUserInfo.estimatedSectionFooterHeight = 0;
    }
    [self.view addSubview:_tbUserInfo];
    
    WLWkSelf
    [_tbUserInfo mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(weakSelf.view);
    }];
}

#pragma mark - UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section==0) {
        return 5;
    }
    else
    {
        return 1;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return WLScaleX(10);
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger row = indexPath.row;
    static NSString *strInfoCell = @"infoCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:strInfoCell];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:strInfoCell];
        cell.textLabel.font = [WLCommonTool fontTypePingFangSCRegular:17];
        cell.textLabel.textColor = wlBlackColor;
        cell.detailTextLabel.font = [WLCommonTool fontTypePingFangSCRegular:14];
        cell.detailTextLabel.textColor = wlLightTextColor;
    }
    
    cell.textLabel.text = arrTitles[indexPath.section][row];
    
//    WLUserInfo *user = [[WLUseManager shareUser] getUserInformation];
    if (indexPath.section == 1) {
        cell.detailTextLabel.text = _user.phone;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    else
    {
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        switch (row) {
            case 0:
            {
                for (UIView *vSub in cell.contentView.subviews) {
                    if ([vSub isKindOfClass:[UIImageView class]]) {
                        [vSub removeFromSuperview];
                    }
                }
                UIImageView *ivHead = [[UIImageView alloc] initWithFrame:CGRectMake(WIDTH_SCREEN_WL-WLScaleX(32+37), WLScaleX(12), WLScaleX(32), WLScaleX(32))];
                ivHead.layer.cornerRadius = WLScaleX(16);
                ivHead.layer.masksToBounds = YES;
                [cell.contentView addSubview:ivHead];
                [ivHead sd_setImageWithURL:[NSURL URLWithString:_user.headImg] placeholderImage:nil];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                
                cell.detailTextLabel.text = @"";
            }
                break;
            case 1:
            {
                cell.detailTextLabel.text = _user.username;
            }
                break;
            case 2:
            {
                if ([_user.sex integerValue]==1) {
                    cell.detailTextLabel.text = @"男";
                }
                else
                {
                    cell.detailTextLabel.text = @"女";
                }
            }
                break;
            case 3:
            {
                if (_user.birthday==nil) {
                    cell.detailTextLabel.text = @"请选择";
                }
                else
                {
                    NSString *strBirth = [WLCommonTool timeNoHMS:[_user.birthday longLongValue]];
                    cell.detailTextLabel.text = strBirth;
                }
            }
                break;
            case 4:
            {
                cell.detailTextLabel.text = _user.email;
            }
                break;
                
            default:
                break;
        }
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section==0) {
        switch (indexPath.row) {
            case 0:
            {
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
                UIImage *imgCached = [[SDImageCache sharedImageCache] imageFromCacheForKey:_user.headImg];
                if (imgCached != nil)
                {
                    UIAlertAction *lookAction = [UIAlertAction actionWithTitle:@"查看头像" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                        WLUserHeadVController *headController = [[WLUserHeadVController alloc] init];
                        headController.headImage = imgCached;
                        [self.navigationController pushViewController:headController animated:YES];
                    }];
    //                [photo setValue:wlblueColor forKey:@"_titleTextColor"];
                    [alertController addAction:lookAction];
                }
                
                UIAlertAction *photo = [UIAlertAction actionWithTitle:@"我的相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    [self chooseHeadimgAction:UIImagePickerControllerSourceTypePhotoLibrary];
                }];
//                [photo setValue:wlblueColor forKey:@"_titleTextColor"];
                [alertController addAction:photo];
                
                UIAlertAction *camera = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    [self chooseHeadimgAction:UIImagePickerControllerSourceTypeCamera];
                }];
//                [camera setValue:wlblueColor forKey:@"_titleTextColor"];
                [alertController addAction:camera];
                
                UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                }];
//                [cancel setValue:wlblueColor forKey:@"_titleTextColor"];
                [alertController addAction:cancel];
                
                [self presentViewController:alertController animated:YES completion:nil];
            }
                break;
            case 1:
            {
                WLUserInfoModifyVController *modifyController = [[WLUserInfoModifyVController alloc] init];
                modifyController.userInfos = _user;
                [self.navigationController pushViewController:modifyController animated:YES];
            }
                break;
            case 2:
            {
                WLWkSelf
                WLGenderSelectView *genderView = [[WLGenderSelectView alloc] init];
                [genderView showGenderSelectViewAction:^(NSInteger index) {
                    [weakSelf updateUserGender:index];
                }];
            }
                break;
            case 3:
            {
                WLDatePicker *picker = [[WLDatePicker alloc] init];
                [picker showWithFrame:CGRectMake(0, HEIGHT_SCREEN_WL-WLScaleX(226), WIDTH_SCREEN_WL, WLScaleX(226)) andDatePickerMode:UIDatePickerModeDate];
                picker.delegate = self;
            }
                break;
            case 4:
            {
                WLUserInfoModifyVController *modifyController = [[WLUserInfoModifyVController alloc] init];
                modifyController.userInfos = _user;
                modifyController.type = 1;
                [self.navigationController pushViewController:modifyController animated:YES];
            }
                break;
                
            default:
                break;
        }
    }
}

- (void)picker:(UIDatePicker *)picker valueChanged:(NSDate *)date
{
    NSDateFormatter *format = [[NSDateFormatter alloc] init];
    format.dateFormat = @"yyyy-MM-dd";
    NSString *strDate = [format stringFromDate:date];
    NSDictionary *params = @{@"birthday":strDate};
    WLWkSelf
    [WLHttpManager WLRequestMethod:RequestTypePost urlStr:@"user/app/edit" withParamsDic:params success:^(NSDictionary *successDict) {
        WLUserInfo *userInfo = [WLUserInfo mj_objectWithKeyValues:successDict[@"object"]];
        [[WLUseManager shareUser] updateUserValue:userInfo];
        weakSelf.user = userInfo;
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:3 inSection:0];
        [weakSelf.tbUserInfo reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
    } failure:^(NSString *errorMsg, NSInteger errorTag) {
        [weakSelf showHUDMessage:errorMsg];
    } error:^(NSError *error) {

    } inView:self.view];
}

- (void)updateUserGender:(NSInteger)gender
{
    NSDictionary *params = @{@"sex":gender==1?@(true):@(false)};
    WLWkSelf
    [WLHttpManager WLRequestMethod:RequestTypePost urlStr:@"user/app/edit" withParamsDic:params success:^(NSDictionary *successDict) {
        WLUserInfo *userInfo = [WLUserInfo mj_objectWithKeyValues:successDict[@"object"]];
        [[WLUseManager shareUser] updateUserValue:userInfo];
        weakSelf.user = userInfo;
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:2 inSection:0];
        [weakSelf.tbUserInfo reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
    } failure:^(NSString *errorMsg, NSInteger errorTag) {
        [weakSelf showHUDMessage:errorMsg];
    } error:^(NSError *error) {
        
    } inView:self.view];
}

- (void)updateUserHeadimg:(NSString *)imgUrl
{
    NSDictionary *params = @{@"headImg":imgUrl};
    WLWkSelf
    [WLHttpManager WLRequestMethod:RequestTypePost urlStr:@"user/app/edit" withParamsDic:params success:^(NSDictionary *successDict) {
        WLUserInfo *userInfo = [WLUserInfo mj_objectWithKeyValues:successDict[@"object"]];
        [[WLUseManager shareUser] updateUserValue:userInfo];
        weakSelf.user = userInfo;
        [weakSelf.tbUserInfo reloadData];
//        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
//        [weakSelf.tbUserInfo reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
    } failure:^(NSString *errorMsg, NSInteger errorTag) {
        [weakSelf showHUDMessage:errorMsg];
    } error:^(NSError *error) {
        
    } inView:self.view];
    return;
}

- (void)chooseHeadimgAction:(UIImagePickerControllerSourceType)type
{
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.sourceType = type;
    imagePickerController.mediaTypes = @[(__bridge NSString *)kUTTypeImage];
    imagePickerController.allowsEditing = YES;
    imagePickerController.navigationBar.translucent=NO;
    [imagePickerController.navigationBar setTintColor:wlBlackColor];
    [self presentViewController:imagePickerController animated:YES completion:nil];
}

#pragma mark - UIImagePickerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    NSString  *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    if ([mediaType isEqualToString:(__bridge NSString *)kUTTypeImage])
    {
        UIImage *selectImage = [info objectForKey:UIImagePickerControllerEditedImage];
//        selectedImg = selectImage;
        NSString *type = @"jpg";
        NSData *data = UIImageJPEGRepresentation(selectImage, 0.5);
        if (data==nil) {
            data = UIImagePNGRepresentation(selectImage);
            type = @"png";
        }
        NSDateFormatter *dateformat=[[NSDateFormatter  alloc]init];
        [dateformat setDateFormat:@"yyMMddHHmmss"];
        NSString *strTime = [dateformat stringFromDate:[NSDate date]];
        NSString *fileName = [NSString stringWithFormat:@"%@.%@",strTime,type];
        
        WLWkSelf
        /*
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html", @"image/jpeg", @"image/png", @"application/octet-stream", @"text/json", nil];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        NSString *urlStr = @"http://47.75.195.106/router/upload/file/upload";
        [manager POST:urlStr parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
//            NSString *fileName = [fileUrl lastPathComponent];
//            [formData appendPartWithFileURL:fileUrl name:[fileName substringToIndex:fileName.length-4] error:nil];
            [formData appendPartWithFileData:data name:@"file" fileName:fileName                                mimeType:@"image/jpeg"];
        } progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSError *err=nil;
            NSDictionary *dicRet = [NSJSONSerialization JSONObjectWithData:responseObject
                                                                   options:NSJSONReadingMutableContainers
                                                                     error:&err];
            if ([[dicRet objectForKey:@"error"] integerValue]==0)
            {
            }
            else
            {
                
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
        }];
        return;
        */
        
        [WLHttpManager WLUpDownloadPost:@"https://www.zeerong.com/router/upload/file/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
            [formData appendPartWithFileData:data name:@"file" fileName:fileName                                mimeType:@"image/jpeg"];
//            NSURL *fileUrl = [NSURL fileURLWithPath:[dict objectForKey:@"imgPath"]];
//            NSString *fileName = [fileUrl lastPathComponent];
//            [formData appendPartWithFileURL:fileUrl name:[fileName substringToIndex:fileName.length-4] error:nil];
        } progress:^(NSProgress *uploadProgress) {
            
        } success:^(NSDictionary *successDict) {
            [weakSelf updateUserHeadimg:successDict[@"url"]];
            [picker dismissViewControllerAnimated:YES completion:^{
                
            }];
        } failure:^(NSString *errorMsg, NSInteger errorTag) {
            [weakSelf showHUDMessage:errorMsg];
        } error:^(NSError *error) {
            
        } inView:picker.view];
    }
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
